<?php
/**
 * Created by PhpStorm.
 * User: yuliang
 * Date: 2017/10/26
 * Time: 下午12:03
 */
namespace app\webapi\controller;

use app\common\controller\Api;
use app\common\R;
use think\Db;

class Video extends Api{

    /**
     * 用户上传图片
     * @return \think\response\Json
     */
    public function uploadImage(){
        $token = input('post.token');
        $uid = input('post.uid');
        $validate = $this->validate(['uid'=>$uid,'token'=>$token],['uid'=> 'require|number','token'=>'require']);
        if($validate !== true){
            return api_error('1000',$validate);
        }
        // 进行用户校验
        $checkToken = $this->checkAuthToken($token);
        if(!$checkToken){
            return api_error('9999','请重新登陆！');
        }
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('image');
        if(is_null($file)){
            return api_error('4001','请选择上传图片！');
        }
        // 移动到框架应用根目录/public/uploads/ 目录下
//        $info = $file->validate(['size'=>15678,'ext'=>'jpg,png,gif'])->move(ROOT_PATH . 'public' . DS . 'uploads');
//        $info = $file->validate(['size'=>15678,'ext'=>'jpg,png,gif'])->move('uploads/image/');
        $info = $file->validate(['ext'=>'jpg,jpeg,png,gif'])->move('uploads/image/');
        if($info){
            // 成功上传后 获取上传信息
            $data['image_url'] = config('image_path').$info->getSaveName();
            return api_return('上传图片成功！',$data);

        }else{
            // 上传失败获取错误信息
            return api_error('4002',$file->getError());
        }
    }


    /**
     * 视频上传
     */
    public function fileUpload()
    {
        $token = input('post.token');
        $uid = input('post.uid');
        $validate = $this->validate(['uid'=>$uid,'token'=>$token],['uid'=> 'require|number','token'=>'require']);
        if($validate !== true){
            return api_error('1000',$validate);
        }
        // 进行用户校验
        $checkToken = $this->checkAuthToken($token);
        if(!$checkToken){
            return api_error('9999','请重新登陆！');
        }
        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        header("Cache-Control: no-store, no-cache, must-revalidate");
        header("Cache-Control: post-check=0, pre-check=0", false);
        header("Pragma: no-cache");

        if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
            exit; // finish preflight CORS requests here
        }
        if (!empty($_REQUEST['debug'])) {
            $random = rand(0, intval($_REQUEST['debug']));
            if ($random === 0) {
                header("HTTP/1.0 500 Internal Server Error");
                exit;
            }
        }

        // header("HTTP/1.0 500 Internal Server Error");
        // exit;
        // 5 minutes execution time
        @set_time_limit(5 * 60);
        // Uncomment this one to fake upload time
        // usleep(5000);
        // Settings
        // $targetDir = ini_get("upload_tmp_dir") . DIRECTORY_SEPARATOR . "plupload";
        $targetDir = 'uploads' . DIRECTORY_SEPARATOR . 'file_material_tmp';
        $uploadDir = 'uploads' . DIRECTORY_SEPARATOR . 'file_material';
        $cleanupTargetDir = true; // Remove old files
        $maxFileAge = 5 * 3600; // Temp file age in seconds
        // Create target dir
        if (!file_exists($targetDir)) {
            @mkdir($targetDir);
        }
        // Create target dir
        if (!file_exists($uploadDir)) {
            @mkdir($uploadDir);
        }
        // Get a file name
        if (isset($_REQUEST["name"])) {
            $fileName = $_REQUEST["name"];
        } elseif (!empty($_FILES)) {
            $fileName = $_FILES["file"]["name"];
        } else {
            $fileName = uniqid("file_");
        }
        $oldName = $fileName;
        $filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;
        // $uploadPath = $uploadDir . DIRECTORY_SEPARATOR . $fileName;
        // Chunking might be enabled
        $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
        $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 1;
        // Remove old temp files
        if ($cleanupTargetDir) {
            if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
            }
            while (($file = readdir($dir)) !== false) {
                $tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;
                // If temp file is current file proceed to the next
                if ($tmpfilePath == "{$filePath}_{$chunk}.part" || $tmpfilePath == "{$filePath}_{$chunk}.parttmp") {
                    continue;
                }
                // Remove temp file if it is older than the max age and is not the current file
                if (preg_match('/\.(part|parttmp)$/', $file) && (@filemtime($tmpfilePath) < time() - $maxFileAge)) {
                    @unlink($tmpfilePath);
                }
            }
            closedir($dir);
        }

        // Open temp file
        if (!$out = @fopen("{$filePath}_{$chunk}.parttmp", "wb")) {
            die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
        }
        if (!empty($_FILES)) {
            if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
            }
            // Read binary input stream and append it to temp file
            if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
            }
        } else {
            if (!$in = @fopen("php://input", "rb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
            }
        }
        while ($buff = fread($in, 4096)) {
            fwrite($out, $buff);
        }
        @fclose($out);
        @fclose($in);
        rename("{$filePath}_{$chunk}.parttmp", "{$filePath}_{$chunk}.part");
        $index = 0;
        $done = true;
        for ($index = 0; $index < $chunks; $index++) {
            if (!file_exists("{$filePath}_{$index}.part")) {
                $done = false;
                break;
            }
        }


        if ($done) {
            $pathInfo = pathinfo($fileName);
            $hashStr = substr(md5($pathInfo['basename']), 8, 16);
            $hashName = time() . $hashStr . '.' . $pathInfo['extension'];
            $uploadPath = $uploadDir . DIRECTORY_SEPARATOR . $hashName;

            if (!$out = @fopen($uploadPath, "wb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
            }
            if (flock($out, LOCK_EX)) {
                for ($index = 0; $index < $chunks; $index++) {
                    if (!$in = @fopen("{$filePath}_{$index}.part", "rb")) {
                        break;
                    }
                    while ($buff = fread($in, 4096)) {
                        fwrite($out, $buff);
                    }
                    @fclose($in);
                    @unlink("{$filePath}_{$index}.part");
                }
                flock($out, LOCK_UN);
            }
            @fclose($out);
            $response = [
                'success' => true,
                'oldName' => $oldName,
                'filePaht' => $uploadPath,
//                'fileSize' => $data['size'],
                'fileSuffixes' => $pathInfo['extension'],
//                'file_id' => $data['id'],
            ];

            // 上传数据入库
            $data['uid'] = $uid;
            $data['title'] = $oldName;
            $data['create_time'] = $data['update_time'] = date('Y-m-d H:i:s',time());
            $data['url'] = config('api_host').'/'.$uploadPath;
            $path = ROOT_PATH.'public/'.$uploadPath;
            $size = filesize($path);
            $data['size'] = get_size($size,'mb');
            $data['ext'] = pathinfo($path, PATHINFO_EXTENSION);
            $result = Db::name('video')->insertGetId($data);
            if($result){
                $response['video_id'] = $result;
                return api_return('操作成功！',$response);
            }else{
                return api_error('404','未知错误！');
            }
//            die(json_encode($response));
        }

        // Return Success JSON-RPC response
        die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}');
    }


    //用户发布视频
    public function releaseVideo(){
        set_time_limit(0);
        $data['video_id'] = $video_id = trim(input('post.video_id'));
        $data['uid'] = $uid = input('post.uid');
        $data['token'] = input('post.token');
        $data['accounts'] = trim(input('post.accounts'),',');
        $video['name'] = $data['name'] = input('post.name');
        $video['description'] = $data['description'] = input('post.description');
        $video['tags'] = $data['tags'] = input('post.tags');
        $video['image'] = $data['image'] = input('post.image');

        // 广告
        $video['ad'] = input('post.ad')?input('post.ad'):0;
        $rule = [
            'video_id' => 'require|number',
            'uid' => 'require|number',
            'token' => 'require',
            'accounts' => 'require',
            'image' => 'require',
            'name' => 'require',
            'description' => 'require',
            'tags' => 'require',
        ];
        $validate = $this->validate($data,$rule);
        if($validate !== true){
            return api_error('1000',$validate);
        }
        // 进行用户校验
        $checkToken = $this->checkAuthToken($data['token']);
        if(!$checkToken){
            return api_error('9999','请重新登陆！');
        }

        // 补充视频信息
        $update = Db::name('video')->where("id =".$data['video_id'])->update($video);
        if(!$update){
            return api_error('4004','填写信息错误，请重试！');
        }

        // 获取账号相关信息
        $info = Db::name('account')->field('id,platform,sort')->where('id','in',$data['accounts'])->select();
        $forms = array_column($info,'platform','id');
        $sorts = array_column($info,'sort','id');
//        var_dump($forms);
//        echo '<br/>';
//        var_dump($sorts);

        // 插入视频分发表
        $platform = explode(',',$data['accounts']);
        $platform = array_unique($platform);
        $tmp = [];
        foreach ($platform as $key){
            $tmp['video_id'] = $data['video_id'];
            $tmp['account_id'] = $key;
            $tmp['uid'] = $data['uid'];
            $tmp['status'] = 0;
            $tmp['platform'] = $forms[$key];
            $tmp['sort'] = $sorts[$key];
            $insertData[] = $tmp;
            unset($tmp);
        }
        $result = model('Release')->insertAll($insertData);
//        $c = exec("/usr/bin/python /data/wwwroot/apichuanchuantv/public/pythonFiles/CCMain.py $uid $video_id");

//        $val = "$uid $video_id";
//
//        $key = 'test_exec';
//
//        R::rpush($key, $val);

        if($result){
            $task['uid'] = $uid;
            $task['video_id'] = $video_id;
            // 注释广告
//            $task['ad'] = input('post.ad')?input('post.ad'):0;
            $task['ad'] = 0;
            Db::name("task")->insert($task);
//            $c = exec("/usr/bin/python /data/sftp/wenmingzhao/pythonFiles/CCMain.py $uid $video_id");
//            $c = exec("/usr/bin/python /data/sftp/wenmingzhao/pythonFiles/ChuanChuanJieKou/CCMain.py $uid $video_id");
            return api_return('操作成功！',array());
        }else{
            return api_error('4003','添加失败！');
        }
    }

    // 分发视频列表
    public function videoList(){
        $data['uid'] = input('post.uid');
        $data['token'] = input('post.token');
        $page = input('post.page')?input('post.page'):1;

        $rule = [
            'uid' => 'require|number',
            'token' => 'require',
        ];
        $validate = $this->validate($data,$rule);
        if($validate !== true){
            return api_error('1000',$validate);
        }
        // 进行用户校验
        $checkToken = $this->checkAuthToken($data['token']);
        if(!$checkToken){
            return api_error('9999','请重新登陆！');
        }


        $videos = Db::table('tv_video')->field('id,name,title,create_time')->where("uid = ".$data['uid'])->page($page,3)->order('create_time desc')->select();
        $count = Db::table('tv_video')->where("uid = ".$data['uid'])->count();
        $result['page'] = ceil($count/3);
        $result['count'] = $count;
        if(!empty($videos)){
            $model = model('Release');
            foreach ($videos as $key=>$value){
                $videos[$key]['child'] = $model->releaseList($value['id']);
            }
            $result['data'] = $videos;
        }else{
            $result['data'] = array();
        }
        return api_return('操作成功！',$result);

    }

    // 视频列表
    public function videoLists(){
        $data['uid'] = input('post.uid');
        $data['token'] = input('post.token');

        $rule = [
            'uid' => 'require|number',
            'token' => 'require',
        ];
        $validate = $this->validate($data,$rule);
        if($validate !== true){
            return api_error('1000',$validate);
        }
        // 进行用户校验
        $checkToken = $this->checkAuthToken($data['token']);
        if(!$checkToken){
            return api_error('9999','请重新登陆！');
        }


        $videos = Db::table('tv_video')->field('id,title,name,url,create_time,size,ext')->where("uid = ".$data['uid'])->order('create_time desc')->select();
        if(!empty($videos)){
            $result['data'] = $videos;
        }else{
            $result['data'] = array();
        }
        return api_return('操作成功！',$result);

    }

    // 用户收益列表
    public function earnings(){
        $data['uid'] = input('post.uid');
        $data['token'] = input('post.token');
        $page = input('post.page')?input('post.page'):1;
        $size = 5;
        $offset = ($page-1)*$size;

        $rule = [
            'uid' => 'require|number',
            'token' => 'require',
        ];
        $validate = $this->validate($data,$rule);
        if($validate !== true){
            return api_error('1000',$validate);
        }
        // 进行用户校验
        $checkToken = $this->checkAuthToken($data['token']);
        if(!$checkToken){
            return api_error('9999','请重新登陆！');
        }
        $model = Db::name("video");
        $count = $model->field("sum(earnings) as money,count(id) as num,sum(play) as play")->where("ad = 1 and uid = ".$data['uid'])->select();
        $num = $model->where("ad = 1 and uid = ".$data['uid'])->count();
        $result['pages'] = ceil($num/$size);
        $result['num'] = $count[0]['num'];
        $result['play'] = $count[0]['play']?$count[0]['play']:0;
        $result['money'] = $count[0]['money']?$count[0]['money']:(string)"0.00";
        $videos = Db::table('tv_video')->field('id,title,name,url,play,earnings')->where("ad = 1 and uid = ".$data['uid'])
            ->order('create_time desc')->limit($offset,$size)->select();
        if(!empty($videos)){
            $result['data'] = $videos;
        }else{
            $result['data'] = array();
        }
        return api_return('操作成功！',$result);
    }
}